﻿using eslib.nnp5;
using MongoDB.Bson;
using Newtonsoft.Json;
using System;
using System.Text;

namespace eslib.nnp5.serializer
{
    /// <summary>
    /// 使用json序列化
    /// </summary>
    public class JsonSerializer : ISerializer
    {
        public T Deserialize<T>(byte[] buf)
            where T : new()
        {
            string json = Encoding.UTF8.GetString(buf);
            return LoadFromString<T>(json);
        }

        public object Deserialize(Type t, byte[] buf)
        {
            string json = Encoding.UTF8.GetString(buf);
            if (t == null) throw new ArgumentException("参数t不能为null");

            try
            {
                //反射GenericJsonConfig.LoadFromString<T>
                Type gJson = GetType();
                var method = gJson.GetMethod(nameof(LoadFromString)).MakeGenericMethod(t);
                return method.Invoke(null, [json]);
            }
            catch (ArgumentException err)
            {
                throw new NNP5Exception("反序列化时参数异常，检查泛型类是否带无参构造方法(泛型参数带new()约束)");
            }
        }

        public byte[] Serialize(object obj)
        {
            string json = Save(obj);
            return Encoding.UTF8.GetBytes(json);
        }



        #region 静态方法

        public static string Save(object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        public static T LoadFromString<T>(string json) where T : new()
        {
            if (json == null || json == "")
                return new T();
            else
                return JsonConvert.DeserializeObject<T>(json);
        }

        #endregion
    }
}
